package com.cbw.cj01.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.httpclient.DefaultMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

@SuppressWarnings("deprecation")
public class CJUtil {
	public static String sendPost(String surl) {
		String result = "";
		try {
			URL url = new URL(surl);
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setDoInput(true);
			result += convertStreamToString(httpConn.getInputStream());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("No result");
		}
		return result;
	}
	public static String getRemoteContents(String url,String encode) {
		String result = "";
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encode);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultMethodRetryHandler());
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("method err :" + getMethod.getStatusLine());
			}
			result += getMethod.getResponseBodyAsString();
//			result += convertStreamToString(getMethod.getResponseBodyAsStream());
			getMethod.releaseConnection();
//			byte[] responseBody = getMethod.getResponseBody();
//			System.out.println(new String (responseBody));
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	public static String convertStreamToString(InputStream in) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuffer buff = new StringBuffer();
		try {
			String line;
			while ( ( line = reader.readLine()) != null ) {
				buff.append(line);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buff.toString();
	}
}
